//
//  AppDelegate.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/1/26.
//

import UIKit
import IQKeyboardManagerSwift
import VTO2Lib

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        /// iOS15 列表头适配
        if #available(iOS 15.0, *) {
            UITableView.appearance().sectionHeaderTopPadding = 0
        }
        
        // 服务协议
        if !CacheManager.manager.containsObject(forKey: AlreadyAgreement) {
            self.setRootVC(identifier: "AgreementViewController")
        }else {
            // 历史链接/可链接
            self.setRootVC(identifier: "ConnectViewController")
        }
        
        // 如果不存在历史数据列表，那么创建
        // 存储数据格式  [时间戳：数据] 和 [时间戳]  再把时间戳key存储起来，方便读取
        if !CacheManager.manager.containsObject(forKey: HistoryData) {
            CacheManager.manager.setValueForKey(HistoryData, [] as NSCoding)
        }
        if !CacheManager.manager.containsObject(forKey: AutoConnect) {
            CacheManager.manager.setValueForKey(AutoConnect, true as NSCoding)
        }
        if !CacheManager.manager.containsObject(forKey: HistoryOfRing) {
            CacheManager.manager.setValueForKey(HistoryOfRing, [] as NSCoding)
        }
        if !CacheManager.manager.containsObject(forKey: OfflineDeviceIndex) {
            CacheManager.manager.setValueForKey(OfflineDeviceIndex, 0 as NSCoding)
        }
        if !CacheManager.manager.containsObject(forKey: AppleHealthUpload) {
            CacheManager.manager.setValueForKey(AppleHealthUpload, false as NSCoding)
        }
        
        IQKeyboardManager.shared.enable = true
        
        return true
    }
    
    func setRootVC(identifier: String) {
        let mainBundle = Bundle.main
        let main = UIStoryboard(name: "Main", bundle: mainBundle)
        let vc = main.instantiateViewController(withIdentifier: identifier)
//        let nav = RNavigationController.init(rootViewController: ViewController.init())
        let nav = RNavigationController.init(rootViewController: vc)
        self.window?.rootViewController = nav
    }
    
    /// app即将退出
    func applicationWillTerminate(_ application: UIApplication) {
        if RManager.manager.currentDevice != nil {
            VTBLEUtils.sharedInstance().cancelConnect()
        }
    }
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return .portrait
    }

}

